<?php
/**
 * Each engineer has a duty to keep the code elegant
 * Created by wolffy.
 * Author @wolffy<13750088090@sina.cn>
 * Date: 2018/10/10
 * Time: 21:27
 */

namespace App\Services;

use App\Repositories\MessageRepository;
use App\Repositories\UserRepository;
use App\Services\JMessage\JMessageService;

class MessageService extends CommonService
{
    protected $messageRepository;
    protected $userRepository;

    public function __construct(MessageRepository $messageRepository, UserRepository $userRepository)
    {
        $this->messageRepository = $messageRepository;
        $this->userRepository = $userRepository;
    }

    /**
     * 发送消息
     * @param $class '消息分类' personal个人 notice公告 activity活动
     * @param $toUserId '接收消息的用户（标识邀请码）'
     * @param $msgType '消息类型：0001个人，0002公告 0003活动'
     * @param $scene '业务场景：1还款计划，2还款收益，3收银，4收银收益，5会员升级，6会员升级收益，7办卡申请，8办卡收益，9公告，10活动'
     * @param $detailId '消息查看详情id'
     * @param $title '发送标题'
     * @param $content '发送内容'
     * @param $imageUrl '图片url'
     * @param $webUrl 'web跳转url'
     * @return mixed
     */
    public function sendMessage($class, $toUserId, $msgType, $scene, $detailId, $title, $content, $imageUrl, $webUrl)
    {
        $data = [
            'to_user_id' => $toUserId,
            'msg_type' => $msgType,
            'scene' => $scene,
            'detail_id' => $detailId,
            'title' => $title,
            'content' => $content,
            'image_url' => $imageUrl,
            'web_url' => $webUrl,
            'create_time' => time()
        ];
        $this->messageRepository->create($data);
        $jMessageService = new JMessageService();
        $toId = '';
        $sendType = '';
        if ($class == 'personal') {
            $toId = $toUserId;
            $sendType = 'single';
        }
        if ($class == 'notice') {
            $toId = '15044666';
            $sendType = 'chatroom';
        }
        if ($class == 'activity') {
            $toId = '15044668';
            $sendType = 'chatroom';
        }
        return $jMessageService->sendTextMessage($toId, $sendType, $content, $msgType,
            $scene, $detailId, $title, $content, $imageUrl, $webUrl);
    }

    /**
     * 获取消息条数
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMessageCount($toUserId)
    {
        $firstPersonal = $this->messageRepository->getAllToScene($toUserId, '0001', 1, 1);
        $firstNotice = $this->messageRepository->getAllToScene('', '0002', 1, 1);
        $firstActivity = $this->messageRepository->getAllToScene('', '0003', 1, 1);
        $data = [
            'personal' => [
                'first' => !empty($firstPersonal) ? $firstPersonal[0] : (object)[],
                'count' => $this->messageRepository->getCount($toUserId, '0001'),//个人
            ],
            'notice' => [
                'first' => !empty($firstNotice) ? $firstNotice[0] : (object)[],
                'count' => 0,//公告
            ],
            'activity' => [
                'first' => !empty($firstActivity) ? $firstActivity[0] : (object)[],
                'count' => 0,//活动
            ],
        ];
        return $this->responseJson(0, $data);
    }

    /**
     * 获取消息列表
     * @param $toUserId
     * @param $msgType
     * @param $page
     * @return \Illuminate\Http\JsonResponse
     */
    public function getProfitList()
    {
        $result = $this->messageRepository->getProfitAll(100);
        $data = [];
        foreach ($result as $key=>$value) {
            if (!empty($value['to_user_id'])) {
                $user = $this->userRepository->byInvitedCode($value['to_user_id']);
                if (!empty($user)) {
                    $mobile = hiddenMobile($user->mobile);
                    $content = $this->resolveScene($mobile, $value['scene'], $value['content']);
                    $data[] = $content;
                }
            }
        }
        shuffle($data);
        return $this->responseJson(0, $data);
    }

    /**
     * 7好友还款收益（好友还款收益），
     * 8好友收银收益（好友收银收益），
     * 9好友办卡收益（好友办卡收益），
     * 10好友升级高级会员收益（好友升级收益），
     * 11好友升级代言人收益（好友升级收益）
     * @param $invitedCode
     * @param $scene
     * @param $content
     */
    protected function resolveScene($mobile, $scene, $content)
    {
        $content = cutStr($content, '获得', -1);
        $amount = cutStr($content, '元', 0);
        $wordPress = '';
        switch ($scene) {
            case 7:
                $wordPress = $mobile . '好友还款获得' . $amount . '元奖励';
                break;
            case 8:
                $wordPress = $mobile . '好友收银获得' . $amount . '元奖励';
                break;
            case 9:
                $wordPress = $mobile . '好友办卡获得' . $amount . '元奖励';
                break;
            case 10:
                $wordPress = $mobile . '好友升级高级会员获得' . $amount . '元奖励';
                break;
            case 11:
                $wordPress = $mobile . '好友升级代言人获得' . $amount . '元奖励';
                break;
        }
        return $wordPress;
    }

    /**
     * 获取消息列表
     * @param $toUserId
     * @param $msgType
     * @param $page
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMessageList($toUserId, $msgType, $page)
    {
        $data = $this->messageRepository->getAllToScene($toUserId, $msgType, $page, 10);
        return $this->responseJson(0, $data);
    }

    /**
     * 批量标记已读
     * @param $ids
     * @param $type
     * @return \Illuminate\Http\JsonResponse
     */
    public function batchFlagRead($ids, $type, $toUserId)
    {
        if (0 == $type) {
            foreach ($ids as $id) {
                $this->messageRepository->updateRead($id, $toUserId);
            }
        }
        if (1 == $type) {
            $this->messageRepository->updateReadAll($toUserId);
        }
        return $this->responseJson(0, []);
    }

    /**
     * 消息模板
     * @param $templateId
     * @param string $bankNo
     * @param string $bankName
     * @param int $money
     * @param string $invitedUserName
     * @param string $toUserId
     * @param int $detailId
     * @param string $imageUrl
     * @param string $webUrl
     * 业务场景：0无，1还款成功（还款计划），12还款成功（每天还款计划），2还款失败（每天还款计划），
     * 3收银成功（收银明细），4收银失败（收银明细），5实名成功（无），6邀请成功（我的推荐），
     * 7好友还款收益（好友还款收益），8好友收银收益（好友收银收益），9好友办卡收益（好友办卡收益），
     * 10好友升级高级会员收益（好友升级收益），11好友升级代言人收益（好友升级收益）
     * @return mixed
     */
    public function messageTemplate($templateId, $toUserId = '', $bankNo = '', $bankName = '',
                                    $money = 0, $invitedUserName = '', $invitedUserMobile = '',
                                    $detailId = 0, $lowestCardMoney = 0, $imageUrl = '', $webUrl = '')
    {
        $headerTitle = '尊敬的龙猫用户：';
        switch ($templateId) {
            case 15:
                $title = '计划提醒';
                $content = $headerTitle . '您的卡尾号' . substr($bankNo, -4) .
                    '（' . $bankName . '）信用卡还款计划创建成功，还款金额：' . $money . '元，请在还款计划执行前保持卡余额' . $lowestCardMoney . '元，祝您生活愉快。';
                $result = $this->sendMessage('personal', $toUserId, '0001', 15, $detailId,
                    $title, $content, $imageUrl, $webUrl);
                break;
            case 1:
                $title = '还款成功提醒';
                $content = $headerTitle . '您的卡尾号' . substr($bankNo, -4) .
                    '（' . $bankName . '）信用卡还款计划已完成，还款金额：' . $money . '元，祝您生活愉快。';
                $result = $this->sendMessage('personal', $toUserId, '0001', 1, $detailId,
                    $title, $content, $imageUrl, $webUrl);
                break;
            case 12:
                $title = '还款成功提醒';
                $content = $headerTitle . '您的卡尾号' . substr($bankNo, -4) .
                    '（' . $bankName . '）信用卡已还款：' . $money . '元，祝您生活愉快。';
                $result = $this->sendMessage('personal', $toUserId, '0001', 12, $detailId,
                    $title, $content, $imageUrl, $webUrl);
                break;
            case 2:
                $title = '还款失败提醒';
                $content = $headerTitle . '您的卡尾号' . substr($bankNo, -4) .
                    '（' . $bankName . '）信用卡还款：' . $money . '元失败，请及时查看并重新制定还款计划。';
                $result = $this->sendMessage('personal', $toUserId, '0001', 2, $detailId,
                    $title, $content, $imageUrl, $webUrl);
                break;
            case 16:
                $title = '消费失败提醒';
                $content = $headerTitle . '您的卡尾号' . substr($bankNo, -4) .
                    '（' . $bankName . '）信用卡消费：' . $money . '元失败，请及时查看并重新制定还款计划。';
                $result = $this->sendMessage('personal', $toUserId, '0001', 2, $detailId,
                    $title, $content, $imageUrl, $webUrl);
                break;
            case 17:
                $title = '消费成功提醒';
                $content = $headerTitle . '您的卡尾号' . substr($bankNo, -4) .
                    '（' . $bankName . '）信用卡消费：' . $money . '元成功，祝您生活愉快。';
                $result = $this->sendMessage('personal', $toUserId, '0001', 2, $detailId,
                    $title, $content, $imageUrl, $webUrl);
                break;
            case 18:
                $title = '计划提醒';
                $content = $headerTitle . '您的卡尾号' . substr($bankNo, -4) .
                    '（' . $bankName . '）信用卡部分还款：' . $money . '元成功，祝您生活愉快。';
                $result = $this->sendMessage('personal', $toUserId, '0001', 2, $detailId,
                    $title, $content, $imageUrl, $webUrl);
                break;
            case 3:
                $title = '收银成功提醒';
                $content = $headerTitle . '您的卡尾号' . substr($bankNo, -4) .
                    '（' . $bankName . '）信用卡收银' . $money . '元已到账，请查询到账储蓄卡。';
                $result = $this->sendMessage('personal', $toUserId, '0001', 3, $detailId,
                    $title, $content, $imageUrl, $webUrl);
                break;
            case 4:
                $title = '收银失败提醒';
                $content = $headerTitle . '您的卡尾号' . substr($bankNo, -4) .
                    '（' . $bankName . '）信用卡收银' . $money . '元失败，请及时查看。';
                $result = $this->sendMessage('personal', $toUserId, '0001', 4, $detailId,
                    $title, $content, $imageUrl, $webUrl);
                break;
            case 5:
                $title = '实名成功提醒';
                $content = $headerTitle . '您已经通过实名认证，感谢您使用龙猫管家。';
                $result = $this->sendMessage('personal', $toUserId, '0001', 5, $detailId,
                    $title, $content, $imageUrl, $webUrl);
                break;
            case 6:
                $title = '邀请成功提醒';
                $content = $headerTitle . '您邀请的(' . hiddenMobile($invitedUserMobile) . ')已完成注册，您将获得更多奖励，加油哟！';
                $result = $this->sendMessage('personal', $toUserId, '0001', 6, $detailId,
                    $title, $content, $imageUrl, $webUrl);
                break;
            case 7:
                $title = '好友还款收益提醒';
                $content = $headerTitle . '您的好友(' . hiddenMobile($invitedUserMobile) . ')还款成功，您获得' . $money . '元的奖励。';
                $result = $this->sendMessage('personal', $toUserId, '0001', 7, $detailId,
                    $title, $content, $imageUrl, $webUrl);
                break;
            case 8:
                $title = '好友收银收益提醒';
                $content = $headerTitle . '您的好友(' . hiddenMobile($invitedUserMobile) . ')收银成功，您获得' . $money . '元的奖励。';
                $result = $this->sendMessage('personal', $toUserId, '0001', 8, $detailId,
                    $title, $content, $imageUrl, $webUrl);
                break;
            case 9:
                $title = '好友办卡收益提醒';
                $content = $headerTitle . '您的好友(' . hiddenMobile($invitedUserMobile) . ')办卡成功，您获得' . $money . '元的奖励。';
                $result = $this->sendMessage('personal', $toUserId, '0001', 9, $detailId,
                    $title, $content, $imageUrl, $webUrl);
                break;
            case 10:
                $title = '好友升级收益提醒';
                $content = $headerTitle . '您的好友(' . hiddenMobile($invitedUserMobile) . ')升级高级会员，您获得' . $money . '元的奖励。';
                $result = $this->sendMessage('personal', $toUserId, '0001', 10, $detailId,
                    $title, $content, $imageUrl, $webUrl);
                break;
            case 11:
                $title = '好友升级收益提醒';
                $content = $headerTitle . '您的好友(' . hiddenMobile($invitedUserMobile) . ')升级代言人，您获得' . $money . '元的奖励。';
                $result = $this->sendMessage('personal', $toUserId, '0001', 11, $detailId,
                    $title, $content, $imageUrl, $webUrl);
                break;
            case 13:
                $title = '账户收益提现成功提醒';
                $content = $headerTitle . '您的账户收益提现' . $money . '元已到账卡尾号' . substr($bankNo, -4) .
                    '（' . $bankName . '）储蓄卡，请及时查看，邀请更多好友使用将获得更多奖励哦。';
                $result = $this->sendMessage('personal', $toUserId, '0001', 13, $detailId,
                    $title, $content, $imageUrl, $webUrl);
                break;
            case 14:
                $title = '账户收益提现失败提醒';
                $content = $headerTitle . '您的账户收益提现' . $money . '元未到账卡尾号' . substr($bankNo, -4) .
                    '（' . $bankName . '）储蓄卡，请及时查看，邀请更多好友使用将获得更多奖励哦。';
                $result = $this->sendMessage('personal', $toUserId, '0001', 14, $detailId,
                    $title, $content, $imageUrl, $webUrl);
                break;
            default:
                $result = true;
                break;
        }
        return $result;
    }

}